/*
 * @Description:axios 请求二次封装
 * @Autor: lcz
 * @LastEditors: lcz
 * @LastEditTime: 2023-10-08 16:58:42
 */
import axios, { InternalAxiosRequestConfig } from "axios";
import { CookieClass } from "@/utils/tools/auth";
import errorHandler from "./errorHandler";

import { Base_Url } from "@/config/const";
import { message } from "antd";

//取消请求 和axios 标识 + JSON.stringify(config.data)
let pending: any = [];
const CancelToken = axios.CancelToken;
let removePending = (config: InternalAxiosRequestConfig<any>) => {
  for (let p in pending) {
    if (pending[p].u === config.url + "&" + config.method) {
      pending[p].f();
      pending.splice(p, 1);
    }
  }
};

// 创建axios实例
const service = axios.create({
  baseURL: Base_Url,
  timeout: 30000 // 请求超时时间
});

// request拦截器
service.interceptors.request.use(
  config => {
    const token = CookieClass.get(`${import.meta.env.VITE_APP_PROJECT_NAME_PREFIX}_token`);
    if (!!token) {
      config.headers["angine-token"] = token; // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    //取消请求 tab切换等
    removePending(config);
    config.cancelToken = new CancelToken(c => {
      // 这里的axios标识我是用请求地址&请求方式拼接的字符串，当然你可以选择其他的一些方式 JSON.stringify(config.data) +
      pending.push({ u: config.url + "&" + config.method, f: c });
    });

    return config;
  },
  error => errorHandler(error)
);

// response 拦截器
service.interceptors.response.use(
  response => {
    removePending(response.config);
    const res = response.data;
    // console.log(res,'22')
    if (res.code != 200) {
      message.error(res.msg);
      return Promise.reject(res.msg);
    }
    //请求不成功操作
    return res;
  },
  error => errorHandler(error)
);
//表示跨域请求时是否需要使用凭证
service.defaults.withCredentials = true;
export default service;
